import 'package:context_menus/context_menus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/index.dart';

import '../../../../../common/models/index.dart';
import '../../../../../common/utils/index.dart';
import '../../../../../common/values/index.dart';
import '../../../../../common/widgets/index.dart';
import '../index.dart';
import 'chat_behavior.dart';
import 'received_msg.dart';
import 'send_msg.dart';

///
/// 消息列表
///
class ChatMsgListWidget extends GetView<ImChatController> {
  const ChatMsgListWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(right: 10.0, left: 10.0),
        child: Obx(() => ScrollConfiguration(
            behavior: const ChatScrollBehavior(),
            child: Align(
                alignment: Alignment.topCenter,
                child: ListView.separated(
                    padding: const EdgeInsets.only(bottom: 10),
                    reverse: true, // 反转
                    shrinkWrap: true,
                    controller: controller.msgListScrollController,
                    itemBuilder: (BuildContext context, int index) {
                      if (index == controller.state.msgList.length) {
                        return controller.state.hasMore
                            ? const Center(
                                child: SizedBox(
                                  height: 24,
                                  width: 24,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 3,
                                  ),
                                ),
                              )
                            : O2UI.noResultView(context);
                      }
                      IMMessage info = controller.state.msgList[index];
                      if (info.createPerson ==
                          O2ApiManager.instance.o2User?.distinguishedName) {
                        return GestureDetector(
                            onTap: () {
                              controller.clickMsgItem(info);
                            },
                            child: ContextMenuRegion(
                              contextMenu: GenericContextMenu(
                                  buttonConfigs: _contextMenuListForItem(info)),
                              child: sendListItemView(context, info, index),
                            ));
                      }
                      return GestureDetector(
                          onTap: () {
                            controller.clickMsgItem(info);
                          },
                          child: ContextMenuRegion(
                              contextMenu: GenericContextMenu(
                                  buttonConfigs: _contextMenuListForItem(info)),
                              child:
                                  receivedLisItemView(context, info, index)));
                    },
                    separatorBuilder: (context, index) {
                      return const SizedBox(height: 1);
                    },
                    itemCount: controller.state.msgList.length + 1)))));
  }

  List<ContextMenuButtonConfig?> _contextMenuListForItem(IMMessage info) {
    List<ContextMenuButtonConfig?> list = [];
    if (info.toBody()?.type == IMMessageType.text.name) {
      list.add(ContextMenuButtonConfig('im_chat_menu_copy'.tr, onPressed: () {
        controller.copyTextMsg(info);
      }));
    }
    // 撤回消息
    if (controller.getImConfig().enableRevokeMsg == true) {
      if (info.createPerson ==
          O2ApiManager.instance.o2User?.distinguishedName) {
        list.add(
            ContextMenuButtonConfig('im_chat_menu_revoke'.tr, onPressed: () {
          controller.revokeMsg(info);
        }));
      } else if (controller.conversationInfo?.type ==
              O2.imConversationTypeGroup &&
          controller.conversationInfo?.adminPerson ==
              O2ApiManager.instance.o2User?.distinguishedName) {
        list.add(ContextMenuButtonConfig('im_chat_menu_revoke_members'.tr,
            onPressed: () {
          controller.revokeMsg(info);
        }));
      }
    }
    return list;
  }

  String _showPersonName(String? person) {
    if (person != null && person.isNotEmpty) {
      if (person.contains("@")) {
        return person.substring(0, person.indexOf("@"));
      }
      return person;
    }
    return "";
  }

  // 接收到的消息格式
  Widget receivedLisItemView(BuildContext context, IMMessage info, int index) {
    var showTime = _showTime(info, index);
    return Column(
      children: [
        const SizedBox(height: 10),
        showTime.isEmpty
            ? Container()
            : Text(showTime, style: Theme.of(context).textTheme.bodySmall),
        Padding(
            padding: const EdgeInsets.only(right: 50.0, top: 5, bottom: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 头像
                InkWell(
                    onTap: () =>
                        controller.clickAvatarToPerson(info.createPerson!),
                    child: SizedBox(
                      width: 50.w,
                      height: 50.w,
                      child: O2UI.personAvatar(info.createPerson!, 25.w),
                    )),
                Expanded(
                    flex: 1,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                            padding: const EdgeInsets.only(left: 10),
                            child: Text(_showPersonName(info.createPerson),
                                style: Theme.of(context).textTheme.bodyLarge)),
                        const SizedBox(height: 5),
                        ReceivedMessageWidget(
                            msgBody: info.toBody()!, msgId: info.id!),
                      ],
                    ))
              ],
            ))
      ],
    );
  }

  // Offset _tapPosition = Offset.zero;

  // void _getTapPosition(TapDownDetails details, BuildContext context) {
  //   RenderObject? obj = context.findRenderObject();
  //   if (obj is RenderBox) {
  //     _tapPosition = obj.globalToLocal(details.globalPosition);
  //     OLogger.d("有位置。。。。");
  //   }
  // }

  // void showPopmenu(IMMessage info, BuildContext context) {
  //   final RenderObject? overlay =
  //       Overlay.of(context)?.context.findRenderObject();
  //   OLogger.d("有位置。。。。$_tapPosition");
  //   showMenu(
  //   context: context,
  //   position: RelativeRect.fromRect(Rect.fromLTWH(_tapPosition.dx, _tapPosition.dy, 30, 30),
  //           Rect.fromLTWH(0, 0, overlay!.paintBounds.size.width,
  //               overlay.paintBounds.size.height)),
  //   items: <PopupMenuEntry>[
  //     PopupMenuItem(child: Text('语文')),
  //     PopupMenuDivider(),
  //     CheckedPopupMenuItem(
  //       child: Text('数学'),
  //       checked: true,
  //     ),
  //     PopupMenuDivider(),
  //     PopupMenuItem(child: Text('英语')),
  //   ]);

  // }

  String _showTime(IMMessage info, int index) {
    var showTime = '';
    DateTime? time = DateTime.tryParse(info.createTime ?? "");
    if (time != null) {
      if (index == 0) {
        //第一条显示时间
        showTime = time.chatMsgShowTimeFormat();
      } else {
        IMMessage lastMsg = controller.state.msgList[index - 1];
        DateTime? lastTime = DateTime.tryParse(lastMsg.createTime ?? "");
        if (lastTime != null && lastTime.difference(time).inMinutes > 1) {
          // 超过一分钟 显示时间
          showTime = time.chatMsgShowTimeFormat();
        }
      }
    }
    return showTime;
  }

  // 发送的消息格式
  Widget sendListItemView(BuildContext context, IMMessage info, int index) {
    var showTime = _showTime(info, index);
    return SizedBox(
        width: double.infinity,
        child: Column(
          children: [
            const SizedBox(height: 10),
            showTime.isEmpty
                ? Container()
                : Text(showTime, style: Theme.of(context).textTheme.bodySmall),
            Padding(
                padding: const EdgeInsets.only(left: 50, top: 5, bottom: 5),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        flex: 1,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const SizedBox(height: 10),
                            SendMessageWidget(
                              msgBody: info.toBody()!,
                              msgId: info.id!,
                            ),
                          ],
                        )),
                    // 头像
                    InkWell(
                      onTap: () =>
                          controller.clickAvatarToPerson(info.createPerson!),
                      child: SizedBox(
                        width: 50.w,
                        height: 50.w,
                        child: O2UI.personAvatar(info.createPerson!, 25.w),
                      ),
                    )
                  ],
                ))
          ],
        ));
  }
}
